<template>
  <div>
    <InfoTable
      title="权限信息"
      :data="permissions"
      :columns="columns"
      :pagination="pagination"
      key-field="id"
      search-placeholder="请输入权限名称或描述"
      create-button-text="创建权限"
      @search="handleSearch"
      @create="handleCreate"
      @action="handleAction"
      @page-change="handlePageChange"
      @batch-delete="handleBatchDelete"
    />
    
    <!-- 创建权限对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建权限"
      width="500px"
      @close="handleCreateDialogClose"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createFormRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="createForm.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="createForm.code" />
        </el-form-item>
        <el-form-item label="URL路径" prop="url">
          <el-input v-model="createForm.url" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model.number="createForm.type" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCreateDialogClose">取消</el-button>
          <el-button type="primary" @click="handleCreateConfirm" :loading="createLoading">
            确认创建
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑权限对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑权限"
      width="500px"
      @close="handleEditDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="editForm.code" />
        </el-form-item>
        <el-form-item label="URL路径" prop="url">
          <el-input v-model="editForm.url" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model.number="editForm.type" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditDialogClose">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm" :loading="editLoading">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import InfoTable from '@/components/InfoTable.vue'
import { ElMessage, ElMessageBox, ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus'
import { getPermissionInfoList, deletePermission, updatePermission, addPermission, searchPermission } from '@/apis/sys.js'

export default {
  name: 'PermissionInfoTemplate',
  components: {
    InfoTable,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton
  },
  data() {
    return {
      permissions: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        { key: 'id', title: '权限ID' },
        { key: 'name', title: '权限名称' },
        { key: 'code', title: '权限标识' },
        { key: 'url', title: 'URL路径' },
        { key: 'type', title: '类型' },
        { key: 'createTime', title: '创建时间' },
        { key: 'updateTime', title: '更新时间' }
      ],
      searchQuery: '',
      // 创建对话框相关
      createDialogVisible: false,
      createLoading: false,
      createForm: {
        name: '',
        code: '',
        url: '',
        type: null
      },
      createFormRules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入URL路径', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入类型', trigger: 'blur' }
        ]
      },
      // 编辑对话框相关
      editDialogVisible: false,
      editLoading: false,
      editForm: {
        id: '',
        name: '',
        code: '',
        url: '',
        type: null
      },
      editFormRules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入URL路径', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入类型', trigger: 'blur' }
        ]
      }
    }
  },
  async mounted() {
    await this.fetchPermissionData()
  },
  methods: {
    async fetchPermissionData() {
      try {
        // 如果有搜索关键词，使用搜索接口
        if (this.searchQuery) {
          const res = await searchPermission(this.searchQuery)
          if (res && res.code === 0) {
            // 搜索接口返回的是直接的数据数组
            let rawData = Array.isArray(res.data) ? res.data : []
            
            // 映射后端字段到前端期望的字段
            this.permissions = rawData.map(item => ({
              ...item,
              id: item.id || '',
              name: item.permissionName || item.name || '',
              code: item.permissionCode || item.code || '',
              description: item.description || ''
            }))
            
            this.pagination.total = this.permissions.length
          } else {
            ElMessage.error(res?.msg || '搜索权限数据失败')
            this.permissions = []
          }
          return
        }
        
        // 没有搜索关键词时，使用分页列表接口
        const params = {
          offset: (this.pagination.current - 1) * this.pagination.pageSize,
          limit: this.pagination.pageSize
        }
        
        const res = await getPermissionInfoList(params)
        if (res && res.code === 0) {
          // 根据响应结构调整数据赋值
          let rawData = res.data?.list || res.data?.records || res.data || []
          
          // 映射后端字段到前端期望的字段
          this.permissions = rawData.map(item => ({
            ...item,
            id: item.id || '',
            name: item.permissionName || item.name || '',
            code: item.permissionCode || item.code || '',
            description: item.description || ''
          }))
          
          this.pagination.total = res.data?.total || this.permissions.length
        } else {
          ElMessage.error(res?.msg || '获取权限数据失败')
          this.permissions = []
        }
      } catch (error) {
        console.error('获取权限数据异常:', error)
        ElMessage.error('获取权限数据异常: ' + (error.message || '未知错误'))
        this.permissions = []
      }
    },
    handleSearch(query) {
      this.searchQuery = query
      this.pagination.current = 1
      this.fetchPermissionData()
    },
    handleCreate() {
      // 显示创建权限对话框
      this.createDialogVisible = true
    },
    handleAction({ action, item }) {
      switch (action) {
        case 'view':
          console.log('查看权限:', item)
          break
        case 'edit':
          this.handleEdit(item)
          break
        case 'delete':
          this.handleDelete(item)
          break
      }
    },
    handleEdit(item) {
      // 填充编辑表单数据（不包括ID字段）
      this.editForm = {
        id: item.id,
        name: item.name || item.permissionName || '',
        code: item.code || item.permissionCode || '',
        url: item.url || '',
        type: item.type !== undefined ? item.type : null
      }
      // 显示编辑对话框
      this.editDialogVisible = true
    },
    handleCreateConfirm() {
      this.$refs.createFormRef.validate(async (valid) => {
        if (valid) {
          this.createLoading = true
          try {
            // 准备创建数据
            const createData = {
              permissionName: this.createForm.name,
              permissionCode: this.createForm.code,
              url: this.createForm.url,
              type: this.createForm.type
            }
            
            const res = await addPermission(createData)
            if (res && res.code === 0) {
              ElMessage.success('权限创建成功')
              this.createDialogVisible = false
              // 重置表单
              this.handleCreateDialogClose()
              // 重新加载数据
              await this.fetchPermissionData()
            } else {
              ElMessage.error(res?.msg || '权限创建失败')
            }
          } catch (error) {
            console.error('创建权限异常:', error)
            ElMessage.error('创建权限异常: ' + (error.message || '未知错误'))
          } finally {
            this.createLoading = false
          }
        }
      })
    },
    handleCreateDialogClose() {
      this.createDialogVisible = false
      this.$refs.createFormRef?.resetFields()
      // 重置表单数据
      this.createForm = {
        name: '',
        code: '',
        url: '',
        type: null
      }
    },
    handleEditConfirm() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          this.editLoading = true
          try {
            // 准备更新数据（包含ID，但不在表单中显示）
            const updateData = {
              id: this.editForm.id,
              permissionName: this.editForm.name,
              permissionCode: this.editForm.code,
              url: this.editForm.url,
              type: this.editForm.type
            }
            
            const res = await updatePermission(updateData)
            if (res && res.code === 0) {
              ElMessage.success('权限修改成功')
              this.editDialogVisible = false
              // 重新加载数据
              await this.fetchPermissionData()
            } else {
              ElMessage.error(res?.msg || '权限修改失败')
            }
          } catch (error) {
            console.error('修改权限异常:', error)
            ElMessage.error('修改权限异常: ' + (error.message || '未知错误'))
          } finally {
            this.editLoading = false
          }
        }
      })
    },
    handleEditDialogClose() {
      this.editDialogVisible = false
      this.$refs.editFormRef?.resetFields()
    },
    handleDelete(item) {
      ElMessageBox.confirm(
        `确定要删除权限 ${item.name} 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const res = await deletePermission(item.id)
          if (res && res.code === 0) {
            ElMessage.success('删除成功')
            // 重新加载数据
            this.fetchPermissionData()
          } else {
            ElMessage.error(res?.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除权限异常:', error)
          ElMessage.error('删除权限异常: ' + (error.message || '未知错误'))
        }
      }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除')
      })
    },
    handlePageChange(page) {
      this.pagination.current = page
      // 清空搜索条件并重新加载数据
      this.searchQuery = ''
      this.fetchPermissionData()
    },
    // 处理批量删除
    handleBatchDelete(selectedItems) {
      console.log('批量删除权限:', selectedItems)
      ElMessage.info(`选择了 ${selectedItems.length} 个权限进行删除`)
      // 这里应该调用批量删除API
    }
  }
}
</script>

<style scoped>
</style>